package com.xbd.wxpay.util;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayOutputStream;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Map;
import java.util.TreeMap;

public class RSAUtil {
    /**
     * RSA最大加密明文大小
     */
    private static final int MAX_ENCRYPT_BLOCK = 117;

    /**
     * RSA最大解密密文大小
     */
    private static final int MAX_DECRYPT_BLOCK = 128;
    /**
     * 默认AES Key 长度
     */
    public static final Integer DEFAULT_AES_KEY_LENGTH = 16;
    /**
     * 生成AES加密所需Key的算法
     */
    private static final String AES_ALGORITHM = "AES";
    /**
     * 加解密算法/工作模式/填充方式,Java6.0支持PKCS5Padding填充方式,BouncyCastle支持PKCS7Padding填充方式
     */
    private static final String AES_PADDING = "AES/CBC/PKCS5Padding";
    /**
     * 默认字符集
     */
    public static final String DEFAULT_CHARSET = "UTF-8";

    /**
     * 获取密钥对
     *
     * @return 密钥对
     */
    public static KeyPair getKeyPair() throws Exception {
        KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
        generator.initialize(1024);
        return generator.generateKeyPair();
    }

    /**
     * 获取私钥
     *
     * @param privateKey 私钥字符串
     * @return
     */
    public static PrivateKey getPrivateKey(String privateKey) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] decodedKey = Base64.decodeBase64(privateKey.getBytes());
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKey);
        return keyFactory.generatePrivate(keySpec);
    }

    /**
     * 获取公钥
     *
     * @param publicKey 公钥字符串
     * @return
     */
    public static PublicKey getPublicKey(String publicKey) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] decodedKey = Base64.decodeBase64(publicKey.getBytes());
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decodedKey);
        return keyFactory.generatePublic(keySpec);
    }

    /**
     * RSA加密
     *
     * @param data      待加密数据
     * @param publicKey 公钥
     * @return
     */
    public static String encrypt(String data, PublicKey publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        int inputLen = data.getBytes().length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offset = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段加密
        while (inputLen - offset > 0) {
            if (inputLen - offset > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(data.getBytes(), offset, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(data.getBytes(), offset, inputLen - offset);
            }
            out.write(cache, 0, cache.length);
            i++;
            offset = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        // 获取加密内容使用base64进行编码,并以UTF-8为标准转化成字符串
        // 加密后的字符串
        return new String(Base64.encodeBase64String(encryptedData));
    }

    /**
     * RSA解密
     *
     * @param data       待解密数据
     * @param privateKey 私钥
     * @return
     */
    public static String decrypt(String data, PrivateKey privateKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] dataBytes = Base64.decodeBase64(data);
        int inputLen = dataBytes.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offset = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段解密
        while (inputLen - offset > 0) {
            if (inputLen - offset > MAX_DECRYPT_BLOCK) {
                cache = cipher.doFinal(dataBytes, offset, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(dataBytes, offset, inputLen - offset);
            }
            out.write(cache, 0, cache.length);
            i++;
            offset = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData = out.toByteArray();
        out.close();
        // 解密后的内容
        return new String(decryptedData, "UTF-8");
    }

    /**
     * sha1WithRsa签名
     *
     * @param data       待签名数据
     * @param privateKey 私钥
     * @return 签名
     */
    public static String sha1Sign(String data, PrivateKey privateKey) throws Exception {
        Signature signature = Signature.getInstance("SHA1WithRSA");
        signature.initSign(privateKey);
        signature.update(data.getBytes());
        return new String(Base64.encodeBase64(signature.sign()));
    }

    /**
     * sha1withRsa验签
     *
     * @param srcData   原始字符串
     * @param publicKey 公钥
     * @param sign      签名
     * @return 是否验签通过
     */
    public static boolean sha1Verify(String srcData, PublicKey publicKey, String sign) throws Exception {
        Signature signature = Signature.getInstance("SHA1WithRSA");
        signature.initVerify(publicKey);
        signature.update(srcData.getBytes());
        return signature.verify(Base64.decodeBase64(sign.getBytes()));
    }

    /**
     * 获取待加签字符串
     *
     * @param params
     * @return
     */
    public static String getSignatureContent(Map<String, Object> params) {
        Map<String, Object> sortedParams = new TreeMap(params);
        StringBuilder content = new StringBuilder();
        int index = 0;
        for (Map.Entry<String, Object> entry : sortedParams.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue().toString();
            if (!StringUtils.isEmpty(value)) {
                content.append(index == 0 ? "" : "&").append(key) .append("=").append(value);
                index++;
            }
        }
        return content.toString();
    }


    /**
     * 生成16bit随机加密aesKey
     * @return
     */
    public static String generateAesKey() {
        return RandomStringUtils.randomAlphanumeric(DEFAULT_AES_KEY_LENGTH);
    }

    /***
     * AES加密
     *
     * @param content 待加密内容
     * @param aesKey 密钥
     * @return
     */
    public static String aesEncrypt(String content, String aesKey) throws Exception {
        IvParameterSpec zeroIv = new IvParameterSpec(aesKey.getBytes());
        SecretKeySpec key = new SecretKeySpec(aesKey.getBytes(DEFAULT_CHARSET), AES_ALGORITHM);
        Cipher cipher = Cipher.getInstance(AES_PADDING);// 创建密码器
        byte[] byteContent = content.getBytes(DEFAULT_CHARSET);
        cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);// 初始化
        // 加密
        byte[] result = cipher.doFinal(byteContent);
        // 转换16进制字符串后返回
        return Base64.encodeBase64String(result);
    }

    /***
     * AES解密，输入密文16进制字符串,默认使用U8编码
     *
     * @param cipherText
     * @param aesKey
     * @return
     */
    public static String aesDecrypt(String cipherText, String aesKey) throws Exception {
        // 将16进制的密文转换为byte类型
        byte[] cipherTextByte = Base64.decodeBase64(cipherText);
        if (cipherTextByte == null) {
            return null;
        }
        IvParameterSpec zeroIv = new IvParameterSpec(aesKey.getBytes(DEFAULT_CHARSET));
        SecretKeySpec key = new SecretKeySpec(aesKey.getBytes(DEFAULT_CHARSET), AES_ALGORITHM);
        Cipher cipher = Cipher.getInstance(AES_PADDING);// 创建密码器
        cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);// 初始化
        byte[] result = cipher.doFinal(cipherTextByte);
        return new String(result, DEFAULT_CHARSET);
    }

    public static void main(String[] args) throws Exception {

    }
}
